// Copyright 2013 Petar Maymounkov
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package sched

import (
	"io"
	"sync"
)

// Quota behaves like sync.Mutex, except it allows up to a given limit of concurrent lock holders.
type Quota struct {
	lk     sync.Mutex
	ch     chan struct{}
	closed bool
}

// NewQuota creates a new quota with limit m.
func NewQuota(m int) *Quota {
	return (&Quota{}).Init(m)
}

// Init resets this limiter and sets its limit to m.
func (q *Quota) Init(m int) *Quota {
	q.ch = make(chan struct{}, m)
	for i := 0; i < m; i++ {
		q.ch <- struct{}{}
	}
	return q
}

// Lock blocks until there are fewer than limit unclosed sessions.
// A session begins when Open returns.
func (q *Quota) Begin() error {
	// Take an execution permit
	if _, ok := <-q.ch; !ok {
		return io.ErrUnexpectedEOF
	}
	return nil
}

// End undoes one previous Begin.
func (q *Quota) End() {
	q.lk.Lock()
	defer q.lk.Unlock()
	// Replace the execution permit
	if q.closed {
		return
	}
	q.ch <- struct{}{}
}

func (q *Quota) Close() {
	q.lk.Lock()
	defer q.lk.Unlock()
	if q.closed {
		return
	}
	close(q.ch)
	q.closed = true
}
